import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';

import 'package:yb_zsyiji_androidflutter_pro/YBNetWorkModule/YBAPi/YBAPi.dart';

Map<String, dynamic> optHeader = {
  "accept-language":'zh-cn',
  'content-type':'application/json'
};



class YBBaseSessionManager  {

  static YBBaseSessionManager _singleton = YBBaseSessionManager._internal();

  factory YBBaseSessionManager() => _singleton;

  //单例模式
  Dio _dio;

  YBBaseSessionManager._internal() {
    if (null == _dio) {
       _dio = Dio();
       _dio.options.baseUrl = YBApi.Base_URL;
       _dio.options.connectTimeout = 30 * 1000;
       _dio.options.sendTimeout = 30 *1000;
       _dio.options.receiveTimeout = 30 *1000;
    }
  }

  //url: 网络请求地址
  //param ：请求参数
  // get 请求
  Future get(String url,{Map<String, dynamic> params, bool isAddLoading = false, BuildContext context, String loadingText}) async {
    Response response;

    Directory documentsDir = await getApplicationDocumentsDirectory();
    String documentsPath = documentsDir.path;
    var dir = Directory("$documentsPath/cookies");
    await dir.create();

    _dio.interceptors.add(CookieManager(PersistCookieJar(dir: dir.path,ignoreExpires: true)));

    //显示 加载中的loading
    if (isAddLoading) {

    }

    try {
      if (params != null) {
        response = await _dio.get(url, queryParameters: params);

      } else {
        response = await _dio.get(url);
      }

      if (response.data["errorCode"] == 0) {
          return response;
      } else {
          String data = response.data["errorMsg"];
      }
    } on DioError catch (e) {
      if (e.response != null) {
        print(e.response.headers);
        print(e.response.request);
      }else{
        print(e.request);
      }
    }
  }


  //url:网络请求地址
  //formData : 请求参数
  //post 请求

  Future post(String url, {FormData formData, Map<String, dynamic> queryParmeters, bool isAddLoading = false, BuildContext context, String loadingText}) async {
    Response response;

    Directory doctumentsDir = await getApplicationDocumentsDirectory();
    String documentsPath = doctumentsDir.path;
    var dir = Directory("$documentsPath/cookies");
    await dir.create();

    _dio.interceptors.add(CookieManager(PersistCookieJar(dir: dir.path)));

    if (isAddLoading) {

    }

    try {
      if (formData != null) {
         response = await _dio.post(url,data: formData);
      } else if (queryParmeters != null) {
         response = await _dio.post(url,queryParameters: queryParmeters);
      }  else {
        response = await _dio.post(url);
      }

      if (response.data["errorCode"] == 0) {
        return response;
      }  else {
        String data = response.data["errorCode"];
      }
    } on DioError catch (e) {
      if (e.response != null) {
         print(e.response.headers);
         print(e.response.request);
      } else {
         print(e.request);
      }
      return null;
    }

  }

  void disMissLoadingDialog(bool isAddLoading, BuildContext context){
    if (isAddLoading) {
      Navigator.of(context).pop();
    }
  }

  //显示Loading
  void showLoadin(BuildContext context, String loadText){
    showDialog(context:context, barrierDismissible:false,builder: (_){
      return ;
    });
  }

  static String handlerError(error,{String defaultErrorStr = '未知错误!!!'}) {
    String errStr;
    if (error is DioError) {
       if (error.type == DioErrorType.CONNECT_TIMEOUT) {
         errStr = "连接超时";
       } else if (error.type == DioErrorType.SEND_TIMEOUT) {
         errStr = "请求超时";
       } else if (error.type == DioErrorType.RECEIVE_TIMEOUT){
         errStr = "响应超时";
       } else if (error.type == DioErrorType.CANCEL) {
         errStr = "请求取消";
       } else if (error.type == DioErrorType.RESPONSE) {
          int statusCode = error.response.statusCode;
          String msg = error.response.statusMessage;

          //异常状态码的处理
          switch(statusCode) {
            case 500:
              errStr = "服务器异常";
              break;
            case 404:
              errStr = "未找到资源";
              break;
            default:
              errStr = '$msg[$statusCode]';
              break;
          }
       }  else if (error.type == DioErrorType.DEFAULT) {
         error = '${error.message}';
         if (error.error is SocketException) {
            errStr = '网络连接超时';
         }
       } else {
         errStr = '未知错误!!!';
       }
    }
    return errStr ?? defaultErrorStr;
  }

}